import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class Message_database{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Massage_database[" +
                from + " 对 " +
                to + "说：" +
                message  +
                ']';
    }
}

@WebServlet("/MessageWallDatabase")
public class MessageWallDatabase extends HttpServlet {
    //定义一个使用将JSON对象转化为Message对象的objectMapper
    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //用于储存从数据库中查询出的Message表中的数据
        try {
            //将数据库中的数据写入到"这个储存消息的list中"
            List<Message_database> message_databasesList=load();
            // 由于约定的请求, 没有参数, 不需要进行任何解析操作~~
            resp.setContentType("application/json;charset=utf8");
            // 把对象转成 json 格式的字符串. 此处 messageList 是一个 List, 直接就被转成 json 数组了.
            String respString = objectMapper.writeValueAsString(message_databasesList);
            resp.getWriter().write(respString);
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Message_database message_database=objectMapper.readValue(req.getInputStream(),Message_database.class);
        System.out.println(message_database);//服务器打印一下
        try {
            //保存这条新的数据到数据库
            saveMessage(message_database);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("message: " + message_database);
        // 3. 返回保存成功的响应
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write("{ \"ok\": 1 }");

    }

    private List<Message_database> load() throws SQLException {
        //DataSource dataSource=DataBaseOperator.getDataSource();
        Connection connection=DataBaseOperator.getConnection();
        //用于接收查询的表结果
        ResultSet resultSet=null;
        List<Message_database> list=new ArrayList<>();
        String sql="select*from message";
        PreparedStatement statement=connection.prepareStatement(sql);
        //执行sql
        resultSet= statement.executeQuery();
        while(resultSet.next()){
            Message_database message_database=new Message_database();
            message_database.from=resultSet.getString("from");
            message_database.to=resultSet.getString("to");
            message_database.message=resultSet.getString("message");
            list.add(message_database);
        }
        return list;
    }

    private void saveMessage(Message_database message) throws SQLException {
        //与数据库建立链接并插入数据
        PreparedStatement statement = null;
        Connection connection=DataBaseOperator.getConnection();
        System.out.println(connection);
        //建立插入的sql语句
        String sql="insert into message values(?,?,?)";
          statement=connection.prepareStatement(sql);
        statement.setString(1,message.from);
        statement.setString(2,message.to);
        statement.setString(3,message.message);
        //执行构建好的sql语句
        int row=statement.executeUpdate();
        if(row==0){
            System.out.println("数据插入失败");
        }else{
            System.out.println("插入成功"+row+"条数据受到影响");
        }
        //释放资源
        DataBaseOperator.close(connection,statement,null);
    }
}
